/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VendaEdicao.java
 *
 * Created on 12/05/2011, 12:49:35
 */
package br.com.softnight.ui;

import br.com.softnight.dao.VendaDAO;
import br.com.softnight.db.DBUtil;
import br.com.softnight.entidades.Cliente;
import br.com.softnight.entidades.ItemVenda;
import br.com.softnight.entidades.Produto;
import br.com.softnight.entidades.Venda;
import br.com.softnight.ui.comboboxmodel.ComboBoxModelCliente;
import br.com.softnight.ui.tablemodel.TableModelBrowserItemVenda;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.TableModelEvent;

/**
 *
 * @author Franklin
 */
public class VendaEdicao extends javax.swing.JDialog {
    private Venda venda = null;
    private ComboBoxModelCliente comboBoxModelCliente = new ComboBoxModelCliente();
    private TableModelBrowserItemVenda tableModelBrowserItemVenda = new TableModelBrowserItemVenda();

    /** Creates new form VendaEdicao */
    public VendaEdicao(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
                
        this.cmbCliente.setModel(this.comboBoxModelCliente);
        this.jTable1.setModel(this.tableModelBrowserItemVenda);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        fldId = new javax.swing.JTextField();
        fldData = new javax.swing.JTextField();
        btnSalva = new javax.swing.JButton();
        btnCancela = new javax.swing.JButton();
        btnInsereItem = new javax.swing.JButton();
        btnExcluiItem = new javax.swing.JButton();
        cmbCliente = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("id");

        jLabel2.setText("Data");

        jLabel3.setText("Pessoa");

        jScrollPane1.setViewportView(jTable1);

        btnSalva.setText("Salvar");
        btnSalva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvaActionPerformed(evt);
            }
        });

        btnCancela.setText("Cancelar");

        btnInsereItem.setText("+");
        btnInsereItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsereItemActionPerformed(evt);
            }
        });

        btnExcluiItem.setText("-");

        cmbCliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnSalva)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancela))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(btnInsereItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnExcluiItem, 0, 0, Short.MAX_VALUE))
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fldId, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fldData, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
                            .addComponent(cmbCliente, javax.swing.GroupLayout.Alignment.TRAILING, 0, 357, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fldId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(fldData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnInsereItem)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnExcluiItem))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalva)
                    .addComponent(btnCancela))
                .addGap(11, 11, 11))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public Venda edita(Long id) throws SQLException {
        VendaDAO vendaDAO = new VendaDAO();

        this.edita(vendaDAO.consultaPorId(id));

        return this.venda;
    }
    
    public Venda edita(Venda venda) throws SQLException {
        this.venda = venda;
        this.abre();

        return this.venda;
    }
    
    private void abre() throws SQLException {
        this.comboBoxModelCliente.atualiza();
        this.tableModelBrowserItemVenda.atualizaVenda(this.venda);
        this.atualizaComponentes();
        
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    
    public void atualizaComponentes() {
        this.fldId.setText(String.valueOf(this.venda.getId()));
        this.cmbCliente.setSelectedItem(this.venda.getCliente() == null ? null : this.venda.getCliente());
        this.fldData.setText(String.valueOf(this.venda.getData()));
    }
    
    public void atualizaModelo() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        
        java.util.Date utilDate = simpleDateFormat.parse(this.fldData.getText());
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        int rowCount = this.jTable1.getModel().getRowCount();
        ArrayList<ItemVenda> itensVenda = new ArrayList<ItemVenda>();
        for (int i = 0; i < rowCount; i++) {
            ItemVenda itemVenda = new ItemVenda();

            itemVenda.setId((Long) this.jTable1.getModel().getValueAt(i, 0));
            itemVenda.setVenda((Venda) this.jTable1.getModel().getValueAt(i, 1));
            itemVenda.setProduto((Produto) this.jTable1.getModel().getValueAt(i, 2));
            itemVenda.setQuantidade((Integer) this.jTable1.getModel().getValueAt(i, 3));
            itemVenda.setValorUnitario((Double) this.jTable1.getModel().getValueAt(i, 4));
            itemVenda.setValorTotal((Double) this.jTable1.getModel().getValueAt(i, 5));

            itensVenda.add(itemVenda);
        }

        this.venda.setId(Long.parseLong(this.fldId.getText()));
        this.venda.setCliente((Cliente) this.cmbCliente.getSelectedItem());
        this.venda.setData(sqlDate);
        this.venda.setItensVenda(itensVenda);
    }

    private void btnSalvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvaActionPerformed
        try {
            this.atualizaModelo();
        } catch (ParseException ex) {
            Logger.getLogger(VendaEdicao.class.getName()).log(Level.SEVERE, null, ex);
        }

        this.setVisible(false);
    }//GEN-LAST:event_btnSalvaActionPerformed

    private void btnInsereItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsereItemActionPerformed
        try {
            ItemVenda itemVenda = new ItemVenda();
            itemVenda.setId(DBUtil.nextID());
            itemVenda.setVenda(this.venda);

            ItemVendaEdicao itemVendaEdicao = new ItemVendaEdicao(null, true);
            itemVendaEdicao.edita(itemVenda);
            
            this.venda.addItemVenda(itemVenda);
            this.tableModelBrowserItemVenda.atualizaVenda(this.venda);
            this.jTable1.tableChanged(new TableModelEvent(this.jTable1.getModel()));
        } catch (SQLException ex) {
            Logger.getLogger(VendaEdicao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnInsereItemActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        System.out.println("CLOSED FECHADO ***");
        System.out.println("   INIT LENGTH=>" + this.getWindowListeners().length);
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        System.out.println("window CLOSING");
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancela;
    private javax.swing.JButton btnExcluiItem;
    private javax.swing.JButton btnInsereItem;
    private javax.swing.JButton btnSalva;
    private javax.swing.JComboBox cmbCliente;
    private javax.swing.JTextField fldData;
    private javax.swing.JTextField fldId;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
